package com.tanhua.manage.service;



import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.mapper.PublishInfoMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.PublishInfo;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.manage.mapper.PublishAuditLogMapper;
import com.tanhua.manage.pojo.PublishAuditLog;
import com.tanhua.manage.pojo.Total;
import com.tanhua.manage.vo.MessageVo;
import com.tanhua.manage.vo.PageResult;
import com.tanhua.manage.vo.PersonInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 林智星
 * @create 2021-06-06 9:07
 */
@Service
@Slf4j
public class MessageAuditService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PublishAuditLogMapper auditLogMapper;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    public PageResult queryMessageList(Integer pagesize, Integer page, String sortOrder, String sortProp, Long id, Long sd, Long ed, String state, Long uid) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        if (!ObjectUtil.isAllNotEmpty(sortOrder, sortProp)) {
            return pageResult;
        }
        IPage<PublishInfo> iPage = new Page(page, pagesize);
        QueryWrapper<PublishInfo> query = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(uid)) {
            query.eq("user_id", uid);
        }
        if (ObjectUtil.isNotEmpty(id)) {
            query.eq("id", id);
        }
        if (ObjectUtil.isAllNotEmpty(sd, ed) && sd > 0 && ed > 0) {
            query.ge("create_date", sd).le("create_date", ed);
        }
        if (ObjectUtil.isNotEmpty(state)) {
            if (!StrUtil.equals("all", state)) {
                query.eq("state", state);
            }
        }
        if (StringUtils.equals(sortOrder, "descending")) {
            query.orderByDesc(underscoreName(sortProp));
        } else {
            query.orderByAsc(underscoreName(sortProp));
        }
        publishInfoMapper.selectPage(iPage, query);
        List<PublishInfo> records = iPage.getRecords();
        List<Total> totals = new ArrayList<>();
        QueryWrapper<PublishInfo> query3 = new QueryWrapper<>();
        query3.eq("state", "3");
        Integer audit = publishInfoMapper.selectCount(query3);
        QueryWrapper<PublishInfo> query4 = new QueryWrapper<>();
        query4.eq("state", "5");
        Integer pass = publishInfoMapper.selectCount(query4);
        QueryWrapper<PublishInfo> query5 = new QueryWrapper<>();
        query5.eq("state", "4");
        Integer reject = publishInfoMapper.selectCount(query5);
        Integer all = audit + pass + reject;
        Total total1 = new Total("全部", "all", all);
        Total total2 = new Total("待审核", "3", audit);
        Total total3 = new Total("已通过", "5", pass);
        Total total4 = new Total("已驳回", "4", reject);
        totals.add(total1);
        totals.add(total2);
        totals.add(total3);
        totals.add(total4);
        pageResult.setCounts(all);
        pageResult.setPages(all / pagesize);
        if (CollUtil.isEmpty(records)) {
            pageResult.setTotals(totals);
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> query2 = new QueryWrapper<>();
        query2.in("user_id", userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(query2);
        List<String> publishId = CollUtil.getFieldValues(records, "publishId", String.class);
        //集合类型转换
        ArrayList<ObjectId> objectIdList = new ArrayList<>();
        for (String s : publishId) {
            objectIdList.add(new ObjectId(s));
        }
        List<Publish> publishList = quanZiApi.queryPublishList(objectIdList);
        List<MessageVo> messageVos = new ArrayList<>();
        for (PublishInfo publishInfo : records) {
            MessageVo vo = new MessageVo();
            vo.setId(publishInfo.getId());
            for (UserInfo userInfo : userInfos) {
                if (publishInfo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    vo.setUserId(Convert.toInt(userInfo.getUserId()));
                    vo.setUserLogo(userInfo.getLogo());
                    vo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            for (Publish publish : publishList) {
                if (StrUtil.equals(publishInfo.getPublishId(), publish.getId().toHexString())) {
                    vo.setText(publish.getText());
                    vo.setMedias(Convert.toStrArray(publish.getMedias()));
                    vo.setCreateDate(Convert.toInt(publish.getCreated()));
                    break;
                }
            }
            //封装createDate
            vo.setState(publishInfo.getState());
            vo.setReportCount(Convert.toInt(publishInfo.getReportCount()));
            vo.setLikeCount(Convert.toInt(publishInfo.getLikeCount()));
            vo.setCommentCount(Convert.toInt(publishInfo.getCommentCount()));
            vo.setForwardingCount(Convert.toInt(publishInfo.getForwardingCount()));
            messageVos.add(vo);
        }
        pageResult.setItems(messageVos);
        pageResult.setTotals(totals);
        return pageResult;
    }

    public static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toLowerCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toLowerCase());
            }
        }
        return result.toString();
    }


    public String messagePass(List<Long> idList) {
        try {
            if (idList.isEmpty()) {
                return null;
            }
//           操作动态额外信息表
            UpdateWrapper<PublishInfo> query = new UpdateWrapper<>();
            query.in("id", idList);
            PublishInfo publishInfo = new PublishInfo();
            publishInfo.setState("5");
            publishInfo.setUpdated(new Date(System.currentTimeMillis()));
            publishInfoMapper.update(publishInfo, query);
//            审核日志表操作
            List<PublishInfo> publishInfos = publishInfoMapper.selectList(query);
            List<String> publishIdList = CollUtil.getFieldValues(publishInfos, "publishId", String.class);
            PublishAuditLog auditLog = new PublishAuditLog();
            auditLog.setTargetState("5");
            auditLog.setUpdated(new Date(System.currentTimeMillis()));
            UpdateWrapper<PublishAuditLog> query2 = new UpdateWrapper<>();
            query2.in("publish_id", publishIdList);
            auditLogMapper.update(auditLog, query2);
            return "操作成功";
        } catch (Exception e) {
            log.info("通过操作失败" + e.getMessage());
        }
        return null;
    }

    public String messageReject(List<Long> idList) {
        try {
            if (idList.isEmpty()) {
                return null;
            }
//           操作动态额外信息表
            UpdateWrapper<PublishInfo> query = new UpdateWrapper<>();
            query.in("id", idList);
            PublishInfo publishInfo = new PublishInfo();
            publishInfo.setState("4");
            publishInfo.setUpdated(new Date(System.currentTimeMillis()));
            publishInfoMapper.update(publishInfo, query);
//            审核日志表操作
            List<PublishInfo> publishInfos = publishInfoMapper.selectList(query);
            List<String> publishIdList = CollUtil.getFieldValues(publishInfos, "publishId", String.class);
            PublishAuditLog auditLog = new PublishAuditLog();
            auditLog.setTargetState("4");
            auditLog.setUpdated(new Date(System.currentTimeMillis()));
            UpdateWrapper<PublishAuditLog> query2 = new UpdateWrapper<>();
            query2.in("publish_id", publishIdList);
            auditLogMapper.update(auditLog, query2);
            return "操作成功";
        } catch (Exception e) {
            log.info("通过操作失败" + e.getMessage());
        }
        return null;
    }

    public String messageRevocation(List<Long> idList) {
        try {
            if (idList.isEmpty()) {
                return null;
            }
//           操作动态额外信息表
            UpdateWrapper<PublishInfo> query = new UpdateWrapper<>();
            query.in("id", idList);
            PublishInfo publishInfo = new PublishInfo();
            publishInfo.setState("3");
            publishInfo.setUpdated(new Date(System.currentTimeMillis()));
            publishInfoMapper.update(publishInfo, query);
//            审核日志表操作
            List<PublishInfo> publishInfos = publishInfoMapper.selectList(query);
            List<String> publishIdList = CollUtil.getFieldValues(publishInfos, "publishId", String.class);
            PublishAuditLog auditLog = new PublishAuditLog();
            auditLog.setTargetState("3");
            auditLog.setUpdated(new Date(System.currentTimeMillis()));
            UpdateWrapper<PublishAuditLog> query2 = new UpdateWrapper<>();
            query2.in("publish_id", publishIdList);
            auditLogMapper.update(auditLog, query2);
            return "操作成功";
        } catch (Exception e) {
            log.info("通过操作失败" + e.getMessage());
        }
        return null;
    }

    public PersonInfoVo queryPersonInfo(Long id) {
        try {
            PersonInfoVo personInfoVo = new PersonInfoVo();
            QueryWrapper<PublishInfo> query = new QueryWrapper<>();
            query.eq("id", id);
            PublishInfo publishInfo = publishInfoMapper.selectOne(query);
            QueryWrapper<UserInfo> query2 = new QueryWrapper<>();
            query2.eq("user_id", publishInfo.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(query2);
            Publish publish = quanZiApi.queryPublishById(publishInfo.getPublishId());
            personInfoVo.setId(Convert.toStr(id));
            personInfoVo.setNickname(userInfo.getNickName());
            personInfoVo.setUserId(Convert.toInt(userInfo.getUserId()));
            personInfoVo.setUserLogo(userInfo.getLogo());
            personInfoVo.setCreateDate(publish.getCreated());
            personInfoVo.setMedias(Convert.toStrArray(publish.getMedias()));
            personInfoVo.setText(publish.getText());
            personInfoVo.setState(Convert.toInt(publishInfo.getState()));
            personInfoVo.setTopState(publishInfo.getTopState() ? 2 : 1);
            personInfoVo.setCommentCount(Convert.toInt(publishInfo.getCommentCount()));
            personInfoVo.setLikeCount(Convert.toInt(publishInfo.getLikeCount()));
            personInfoVo.setReportCount(Convert.toInt(publishInfo.getReportCount()));
            personInfoVo.setForwardingCount(Convert.toInt(publishInfo.getForwardingCount()));
            return personInfoVo;
        } catch (Exception e) {
            log.info("个人信息查询失败" + e.getMessage());
        }
        return null;
    }
}
